package com.qywx.controller;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.qywx.entity.UserEntity;
import com.qywx.service.UserService;
import com.qywx.utils.EasyPoiExcelUtil;
import com.qywx.utils.R;
import com.qywx.utils.RestTemplateUtil;
import com.qywx.utils.WebExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description: 部门成员管理
 * @Author wmj
 * @Date 2020/3/4
 * @Version V1.0
 **/
@Api(value = "成员接口管理", tags = {"成员接口管理"})
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RestTemplateUtil restTemplateUtil;

    /**
     * @MethodName: save
     * @Description: 创建部门成员
     * @Param: [user]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/5
    **/
    @PostMapping("/save")
    @ApiOperation(value = "创建成员", notes = "用户账号(userid),用户名称(name),部门(department)，多个部门以逗号分隔。外部人员属于任何部门")
    public R save(@RequestBody UserEntity user){
        return userService.saveUser(user);
    }

    /**
     * @MethodName: saveToWechat
     * @Description: 一键同步到微信
     * @Param: [user：, deptId]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/5
     **/
    @PostMapping("/save/wechat")
    @ApiOperation(value = "一键同步到微信", notes = "userid:用户账号（userid）,name:用户名称,department:部门id，多个部门以逗号分隔")
    public R saveToWechat(@RequestBody UserEntity user){
        return userService.saveToWechat(user);
    }

    /**
     * @MethodName: findByName
     * @Description: 根据员工姓名搜索
     * @Param: [user：, deptId]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/5
     **/
    @ApiOperation(value = "根据姓名查找成员", notes = "name:用户名称")
    @GetMapping("/find/name")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", required = true, value = "用户名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "depid", required = true, value = "部门id", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "usertype", required = true, value = "用户类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "stat", required = true, value = "有效/无效", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", required = true, value = "激活/未激活", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "id", required = true, value = "id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "category", required = true, value = "职位", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "gender", required = true, value = "性别", paramType = "query", dataType = "String")
    })
    public R findByName(@RequestParam("name") String name,@RequestParam("depid")int depid,@RequestParam("usertype") String usertype,
                        @RequestParam("stat") String stat,@RequestParam("status") String status,@RequestParam("id") String id,
                        @RequestParam("category") String category,@RequestParam("gender") String gender){
        List<UserEntity> userEntity = userService.findByName(name,depid,usertype,stat,status,id,category,gender);
        R r = new R();
        r.put("data",userEntity);
        return r;
    }

    /**
     * @MethodName: findByUserid
     * @Description: 根据用户id查询用户详情
     * @Param: [userid]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/9
     **/
    @ApiOperation(value = "查看成员详情", notes = "userid，成员账号（userid）")
    @GetMapping("/find/userid")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, value = "用户账号（userid）", paramType = "query", dataType = "String")
    })
    public R findByUserid(@RequestParam("userid") String userid){
        return userService.findByUserid(userid);
    }

    /**
     * @MethodName: updateUser
     * @Description: 更新成员
     * @Param: [user]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/5
     **/
    @PostMapping("/update")
    @ApiOperation(value = "更新成员", notes = "")
    public R updateUser(@RequestBody UserEntity user){
        return userService.updateUser(user);
    }

    /**
     * @MethodName: delUserByUserIds
     * @Description: 批量删除成员
     * @Param: userIds（1,2,3）
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/9
     **/
    @GetMapping("/delete")
    @ApiOperation(value = "删除成员", notes = "userid:成员账号（userid）成员id已逗号隔开")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userIds", required = true, value = "用户账号（userid）用户id已逗号隔开", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "usertype", required = true, value = "用户类型", paramType = "query", dataType = "String")
    })
    public R delUserByUserIds(@RequestParam("userIds") String userIds,@RequestParam("usertype") String usertype){
        return userService.delUserByUserIds(userIds,usertype);
    }

    //根据部门id获取部门成员
    @GetMapping("/find/department")
    @ApiOperation(value = "根据部门id查询成员", notes = "departmentId：部门id，page：当前页码，size:每页显示条数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", required = true, value = "部门id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", required = true, value = "当前页码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", required = true, value = "每页显示条数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "status", required = true, value = "激活/未激活", paramType = "query", dataType = "String")
    })
    public R findByDepartmentId(@RequestParam("departmentId") String departmentId,@RequestParam("page") int page,
                                @RequestParam("size") int size,@RequestParam("status") String status){
        return userService.findByDepartmentId(departmentId,page,size,status);
    }

    //获取所有成员,未加筛选条件
    @GetMapping("/find/all")
    @ApiOperation(value = "成员管理", notes = "page：当前页码，size:每页显示条数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", required = true, value = "当前页码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", required = true, value = "每页显示条数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "usertype", required = true, value = "用户类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "stat", required = true, value = "有效/无效", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", required = true, value = "激活/未激活", paramType = "query", dataType = "String"),
    })
    public R findUser(@RequestParam("page") int page,@RequestParam("size") int size,@RequestParam("usertype") String usertype,
                      @RequestParam("stat") String stat,@RequestParam("status") String status){
        return userService.findUserCondition(page,size,usertype,stat,status);
    }

    //获取所有成员
    /*@GetMapping("/find/user/condition ")
    @ApiOperation(value = "人员管理", notes = "page：当前页码，size:每页显示条数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", required = true, value = "当前页码", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", required = true, value = "每页显示条数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "usertype", required = true, value = "用户类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "stat", required = true, value = "有效/无效", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", required = true, value = "激活/未激活", paramType = "query", dataType = "String")
    })
    public R findUserCondition (@RequestParam("page") int page,@RequestParam("size") int size,@RequestParam("usertype") String usertype,
                      @RequestParam("stat") String stat,@RequestParam("status") String status){
        return userService.findUserCondition(page,size,usertype,stat,status);
    }*/
    /**
     * @MethodName: asynchronousDetection
     * @Description: 异步检测
     * @Param: []
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/11
     **/
    @ApiOperation(value = "异步检测", notes = "")
    @GetMapping("/asynchronous/detection")
    public R asynchronousDetection(){
        return userService.asynchronousDetection();
    }
    /**
     * @MethodName: exchangeDepartment
     * @Description: 异步检测
     * @Param: []
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/11
     **/
    @GetMapping("/synchronize")
    @ApiOperation(value = "异步检测后同步", notes = "")
    public R synchronize(){
        return userService.synchronize();
    }

    @GetMapping("/export")
    @ApiOperation(value = "部门成员导出", notes = "id:部门id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", required = true, value = "部门id", paramType = "query", dataType = "Long"),
    })
    public void export(@RequestParam("departmentId") String departmentId, HttpServletResponse response) throws Exception {
        List<UserEntity> userEntityList = userService.export(departmentId);
        EasyPoiExcelUtil.exportExcel(userEntityList,"部门成员信息统计","部门成员信息",UserEntity.class,"部门成员.xlsx",response);
    }

    @GetMapping("/export/id")
    @ApiOperation(value = "成员导出", notes = "成员id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, value = "成员id，不传导出所有成员，筛选id以逗号隔开", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "usertype", required = true, value = "成员类型", paramType = "query", dataType = "String"),
    })
    public void exportByUserId(@RequestParam("userid") String userid,@RequestParam("usertype") String usertype, HttpServletResponse response) throws Exception {
        List<UserEntity> userEntityList = userService.exportByUserId(userid,usertype);
        EasyPoiExcelUtil.exportExcel(userEntityList,"部门成员信息统计","部门成员信息",UserEntity.class,"部门成员.xlsx",response);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "导入", notes = "id:部门id")
    public R upload(MultipartFile file, HttpServletRequest request) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        List<UserEntity> list;
        try {
            // excel的数据
            list = WebExcelUtil.importExcel(file, 1, 1, UserEntity.class);
            return  userService.save(list);
        } catch (Exception e) {
            e.printStackTrace();
            String message = e.getMessage();
            System.out.println(message);
            if(message.contains("PRIMARY")){
                return R.error("账号已存在");
            }
            if(message.contains("mobile")){
                return R.error("手机号已存在");
            }
            if(message.contains("'userid' cannot be null")){
                return R.error("账号不能为空");
            }
            return R.error("导入失败");
        }
    }

    @GetMapping("/export/template")
    @ApiOperation(value = "导出部门成员模板", notes = "")
    public void exportTemplate(HttpServletResponse response) throws Exception {
        List<UserEntity> userEntityList = new ArrayList<UserEntity>();
        UserEntity userEntity = new UserEntity();
        userEntity.setName("张三");
        userEntity.setUserid("zhangsan");
        userEntity.setAlias("zhangsan");
        userEntity.setPosition("主任");
        userEntity.setDepName("骨科/眼科");
        userEntity.setGender("男");
        userEntity.setMobile("13311111111");
        userEntity.setTelephone("021-111111");
        userEntity.setEmail("123456@qq.com");
        userEntity.setAddress("上海");
        userEntityList.add(userEntity);
        EasyPoiExcelUtil.exportExcel(userEntityList,"通讯录批量导入模板","成员列表",UserEntity.class,"通讯录批量导入模板.xlsx",response);
    }

    @GetMapping("/invite")
    @ApiOperation(value = "邀请成员", notes = "userid")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, value = "成员账号", paramType = "query", dataType = "String"),
    })
    public R invite(@RequestParam("userid") String userid) {
        return userService.invite(userid);
    }

    @GetMapping("/add/user/tag")
    @ApiOperation(value = "给人员添加标签", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, value = "成员id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "tagid", required = true, value = "标签id,多个id以逗号隔开", paramType = "query", dataType = "String")
    })
    public R addUserTag(@RequestParam("userid") String userid,@RequestParam("tagid") String tagid) {
        return userService.addUserTag(userid,tagid);
    }

    @GetMapping("/get/mobile")
    @ApiOperation(value = "获取手机号", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", required = true, value = "手机号", paramType = "query", dataType = "String"),
    })
    public R getMobile(@RequestParam("mobile") String mobile) {
        return userService.getMobile(mobile);
    }

    @GetMapping("/update/user/tag")
    @ApiOperation(value = "修改人员添加标签", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, value = "成员id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "delTagid", required = true, value = "需要删除的标签id,多个id以逗号隔开 1，2，3", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "saveTagid", required = true, value = "需要新增的标签id,多个id以逗号隔开1，2，3", paramType = "query", dataType = "String")
    })
    public R updateUserTag(@RequestParam("userid") String userid,@RequestParam("delTagid") String delTagid,@RequestParam("saveTagid") String saveTagid) {
        return userService.updateUserTag(userid,delTagid,saveTagid);
    }

    @GetMapping("/update/stat")
    @ApiOperation(value = "恢复用户为有效", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, value = "成员id", paramType = "query", dataType = "String")
    })
    public R updateStat(@RequestParam("userid") String userid) {
        return userService.updateStat(userid);
    }
    //20201102-start
    /**
     * @MethodName: updateUser
     * @Description: 更新本平台成员
     * @Param: [user]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/5
     **/
    @PostMapping("/updateThisPlatformUser")
    @ApiOperation(value = "更新本平台成员", notes = "")
    public R updateThisPlatformUser(@RequestBody UserEntity user){
        return userService.updateThisPlatformUser(user);
    }

    /**
     * @MethodName: updateWechatUser
     * @Description: 更新企业微信成员
     * @Param: [user]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/5
     **/
    @PostMapping("/updateWechatUser")
    @ApiOperation(value = "更新企业微信成员", notes = "")
    public R updateWechatUser(@RequestBody UserEntity user){
        return userService.updateWechatUser(user);
    }

    /**
     * @MethodName: findByUserid
     * @Description: 根据用户id对比
     * @Param: [userid]
     * @Return: com.qywx.utils.R
     * @Author: wmj
     * @Date: 2020/3/9
     **/
    @ApiOperation(value = "根据用户id对比", notes = "userid，成员账号（userid）")
    @GetMapping("/contrast/userid")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", required = true, value = "用户账号（userid）", paramType = "query", dataType = "String")
    })
    public R findWechatUser(@RequestParam("userid") String userid){
        Map<String,Object> result = new HashMap<>();
        String accessToken = restTemplateUtil.getaccessToken();
        //去微信端查询部门成员是否存在（防止存入用户未同步到微信，直接更新用户）
        String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&userid=" + userid;
        Map resultMap = restTemplate.getForObject(getUrl, Map.class);
        String departmentArray = (String) resultMap.get("department").toString();
        String substring = departmentArray.substring(1, departmentArray.length() - 1);
        String[] split = substring.split(",");
        StringBuffer departments = new StringBuffer();
        for (int j = 0; j < split.length; j++) {
            departments.append(split[j].trim()).append(",");
        }
        String department = departments.substring(0, departments.length() - 1);
        //将部门id转换成部门名称
        String depName = userService.trans(department);
        resultMap.put("department",department);
        resultMap.put("depName",depName);
        result.put("wechatData",resultMap);
        R r = this.findByUserid(userid);
        Object data = r.get("data");
        result.put("systemData",data);
        return R.ok(result);
    }
    //20201102-end
}
